package qdu.rg012.testvp;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;

/**
 * viewpager可以理解为一个容器，期内不得item涉及到数据源 适配器 以及适配器中设定的显式方式
 */
public class TestVP extends Activity {
    List<Color> datalist;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ly_testvp);

        datalist = new ArrayList<Color>();
        initdata();

        ViewPager vp = findViewById(R.id.vp_test);
        vp.setAdapter(new Myvpadp());
    }
    class Myvpadp extends PagerAdapter{

        @Override
        public int getCount() {
            if(datalist != null) {
                Log.i("mytag", "datasize:" + datalist.size());
                return datalist.size();
            }
            else
                return 0;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            //super.instantiateItem(container, position);
            ImageView imgv = new ImageView(TestVP.this);
            if(datalist != null) {
                Log.i("mytag", datalist.get(position).toArgb()+"");
                imgv.setBackgroundColor(datalist.get(position).toArgb());
                container.addView(imgv);
            }
            return imgv;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            //super.destroyItem(container, position, object);

            container.removeView((ImageView)object);
        }
    }

    public void initdata(){
        datalist.add(Color.valueOf(Color.RED));
        datalist.add(Color.valueOf(Color.GREEN));
        datalist.add(Color.valueOf(Color.YELLOW));
        datalist.add(Color.valueOf(Color.BLUE));
    }
}
